#!/usr/bin/python
#
# Copyright 2011 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""GIT API client

Defines the GIT interaction with Open Auth Server.
"""

__author__ = 'Xin Zhou(zhounew@google.com)'

from git.data import git_assertion
from git.json import git_json

import urllib2

class GitApiClient(object):
  def __init__(self, apiKey):
    self.VERIFY_URL = 'https://www.googleapis.com/identitytoolkit/v1/relyingparty/verifyAssertion?key='
    self.apiKey = apiKey;
  
  def post(self, postData):
    '''Sends post HTTP request to the remote URL.
    '''
    try:
      params = git_json.GitJson().dumps(postData)
      cookies = urllib2.HTTPCookieProcessor()
      opener = urllib2.build_opener(cookies)
      request = urllib2.Request(url = self.VERIFY_URL + self.apiKey,
                                headers = {'Content-Type':
                                           'application/json'},
                                data = params)
      response = opener.open(request)
      
      out = response.read()
      return git_json.GitJson().loads(out)
    except urllib2.URLError, e:
      return None
    except Exception, e:
      return None
  
  def verify(self, url, postBody):
    '''Sends request to the identity toolkit API end point to verify the IDP
       response.
    '''
    try:
      data = {}
      data['requestUri'] = url
      data['postBody'] = postBody
      
      response = self.post(data)
      
      if response:
        if not 'identifier' in response:
          return None
        
        verified_email = None
        
        if 'verifiedEmail' in response:
          verified_email = response['verifiedEmail']
        assertion = git_assertion.GitAssertion(response['identifier'],
                                               verified_email)
        if 'firstName' in response:
          assertion.SetFirstName(response['firstName'])
        
        if 'lastName' in response:
          assertion.SetLastName(response['lastName'])
            
        if 'profilePicture' in response:
          assertion.SetPhotoUrl(response['profilePicture'])
        
        if 'fullName' in response:
          assertion.SetFullName(response['fullName'])
        
        if 'nickName' in response:
          assertion.SetNickName(response['nickName'])
        return assertion
      return None
    except Exception, e:
      return None